<?php
/*
All rights Reserved, Designed By www.youyacao.com
@Description:邀请
@author:成都市一颗优雅草科技有限公司
@version 优雅草松鼠聚合直播系统
需要商业用途或者定制开发等可访问songshu.youyacao.com  联系QQ:2853810243 422108995 23625059584
正版系统查询系统 zhengbancha.youyacao.com
 */
namespace app\admin\controller;
use \think\Db;
use \think\Validate;

class Visitor
{
    public function login()
    {
        //进入此接口则登陆ID清空
        session('login_user_id',0);

        $request = request();

        if($request->method() != 'POST') return ['code'=>-1,'msg'=>'请求方法错误'];
        if(!captcha_check($request->param('yzcode'))){
            return ['code'=>-1,'msg'=>'验证码不正确'];
        };
        $rule = [
            'username'  => 'require|min:5|max:20',
            'password'   => 'require|min:6|max:50',
        ];
        $msg = [
            'username.require' => '登陆账号为必填项',
            'username.min'     => '登陆账号至少为5个字符',
            'username.max'     => '登陆账号不能超过20个字符',
            'password.require' => '登陆密码为必填项',
            'password.min'     => '登陆密码至少为6个字符',
            'password.max'     => '登陆密码不能超过50个字符',
        ];
        $data = [
            'username'  => input('username'),
            'password'   => input('password')
        ];
        $validate = new Validate($rule,$msg);
        $result   = $validate->check($data);
        if(!$result){
            return ['code'=>-1,'msg'=>$validate->getError()];
        }
        $user = Db::table('kl_user')->where('username',input('username'))->where('password',md5(input('password')))
            ->where('user_type','between','admin,daili')->field('id,username,usernick,tuijianma,money,user_type,delete_time')->find();
        if(!$user){
            return ['code'=>-1,'msg'=>'用户名或密码不对'];
        }
        if($user['delete_time']>0) return ['code'=>-1,'msg'=>'此账号已被封停，禁止登陆'];
        session('login_user_id',$user['id']);
        //更新登陆时间
        db("user")->where('id',$user['id'])->update(['last_login_time'=>time()]);
        $user['last_login_time'] = date('Y-m-d H:i:s');
        return ['code'=>1,'msg'=>'登陆成功','data'=>$user];
    }

    private function get_yqm($len=10){
        $str = "asdfghjklzxcvbnmoiuytrewqMNBVCXZASDFGHJKLPOIUYTREWQ0987654123";
        $yqm = "";
        for($i=0;$i<$len;$i++){
            $offset = mt_rand(0,strlen($str));
            $yqm .= substr($str,$offset,1);
        }
        return $yqm;
    }

    protected function get_client_ip($type = 0) {
        $type       =  $type ? 1 : 0;
        static $ip  =   NULL;
        if ($ip !== NULL) return $ip[$type];
        if(isset($_SERVER['HTTP_X_REAL_IP'])){//nginx 代理模式下，获取客户端真实IP
            $ip=$_SERVER['HTTP_X_REAL_IP'];
        }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {//客户端的ip
            $ip     =   $_SERVER['HTTP_CLIENT_IP'];
        }elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {//浏览当前页面的用户计算机的网关
            $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos    =   array_search('unknown',$arr);
            if(false !== $pos) unset($arr[$pos]);
            $ip     =   trim($arr[0]);
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip     =   $_SERVER['REMOTE_ADDR'];//浏览当前页面的用户计算机的ip地址
        }else{
            $ip=$_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u",ip2long($ip));
        $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }

    public function register(){
        //进入此接口则登陆ID清空
        session('login_user_id',0);

        if(!request()->isPost()) $this->error('请求类型有误');

        $tuijianma = input("yzcode");
        if(strlen($tuijianma) == 0) return ['code'=>-1,'msg'=>'请填写邀请码'];
        $uid = intval(Db::name('user')->where('tuijianma',$tuijianma)->where("user_type","admin")->value('id'));
        if($uid == 0) return ['code'=>-1,'msg'=>'邀请码不正确，邀请码请向管理员索取'];
        $username = input("username");
        $password = input("password");
        $repassword = input("repassword");
        if(strlen($username) <=5 ) return ['code'=>-1,'msg'=>'代理账号必填且不能小于6位'];
        //if(!preg_match("/^1[34578]\d{9}$/", $username)) return ['code'=>-1,'msg'=>'请填写正确的手机号'];
        if(strlen($password) <=5 ) return ['code'=>-1,'msg'=>'密码必填且不能小于6位'];
        if($password != $repassword) return ['code'=>-1,'msg'=>'两次密码不一致'];

        $finduid = intval(Db::name('user')->where('username',$username)->value('id'));
        if($finduid>0) return ['code'=>-1,'msg'=>'此账号名已注册，不能重复注册'];

        $data = array();
        $data['username'] = $username;
        $data['password'] = md5($password);
        $data['parent_id'] = $uid;
        $data['reg_time'] = time();
        $data['usernick'] = $username;
        $data['reg_ip'] = $this->get_client_ip();
        $data['user_type'] = 'daili';
        $data['regcode'] = $tuijianma;
        $value = $this->get_yqm();
        while(Db::name("user")->where('tuijianma',$value)->find()){
            $value = $this->get_yqm();
        }
        $data['tuijianma'] = $value;
        Db::startTrans();
        try {
            if (Db::name("user")->insert($data)) {
                $uid = Db::getLastInsID();
                $data = array();
                $data['user_id'] = $uid;
                $data['free_times'] = 0;
                if (Db::name("member_info")->insert($data)) {
                    Db::commit();
                    return ['code' => 1, 'msg' => '注册成功'];
                }else{
                    Db::rollback();
                    return ['code' => -1, 'msg' => '未知错误，注册失败'];
                }
            } else {
                return ['code' => -1, 'msg' => '未知错误，注册失败'];
            }
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();//var_dump($e);
            return ['code' => -1, 'msg' => '未知错误，注册失败'];
        }
    }

    public function logout(){
        session('login_user_id',0);
        return ['code'=>1,'msg'=>'成功退出','data'=>NULL];
    }
}
